﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Net;
using System.Net.Mail;
using SES.CMS.BL;
using SES.CMS.DO;
using System.Net.Configuration;
using System.Web.SessionState;

namespace SES.CMS
{
    public partial class ThanhToan : BasePage
    {
        ClientLoginDO obj = new ClientLoginDO();
        ShopingCart vpp = new ShopingCart();
        private static DataTable tb = new DataTable();
        private DataTable dt = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            loadGioHang();
            LoadThongTinThanhToan();
        }
        protected void loadGioHang()
        {
            Page.Title = "Thanh toán - KMA";
            if (Session["GioHang"] != null)
            {
                tb = (DataTable)Session["GioHang"];
                DataTable dt = new DataTable();
                dt.Columns.Add("STT");
                dt.Columns.Add("SanPhamID");
                dt.Columns.Add("TenSanPham");
                dt.Columns.Add("HinhAnh");
                dt.Columns.Add("SoLuong");
                dt.Columns.Add("DonGia");
                dt.Columns.Add("GiamGia");
                dt.Columns.Add("ThanhTien");

                int i = 0;
                foreach (DataRow dr in tb.Rows)
                {
                    cmsSanPhamDO obj = new cmsSanPhamBL().Select(new cmsSanPhamDO { SanPhamID = Int64.Parse(dr[1].ToString()) });
                    i++;
                    DataRow row = dt.NewRow();
                    row[0] = dr[0];
                    row[1] = dr[1];
                    row[3] = obj.HinhAnh;
                    row[4] = dr[2];
                    row[6] = obj.GiamGia;
                    if (Session["lang"].ToString() == "VN")
                    {
                        row[2] = obj.TenSanPham;
                        row[5] = obj.DonGia;
                        float price = obj.DonGia * (100 - obj.GiamGia) / 100;
                        row[7] = price * int.Parse(dr[2].ToString());
                    }
                    else
                    {
                        row[2] = obj.eTenSanPham;
                        float curr = float.Parse(new sysConfigBL().Select(new sysConfigDO { ConfigID = 4 }).ConfigValue) / float.Parse(new sysConfigBL().Select(new sysConfigDO { ConfigID = 4 }).eConfigValue);
                        row[5] = (obj.DonGia) / curr;
                        float price = float.Parse(row[5].ToString()) * (100 - int.Parse(row[6].ToString())) / 100;
                        row[7] = int.Parse(dr[2].ToString()) * price; ;
                    }
                    dt.Rows.Add(row);
                }

                if (dt.Rows.Count > 0)
                {
                    GridGioHang.DataSource = dt;
                    GridGioHang.DataBind();
                    float sum = 0;
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        Label lb = GridGioHang.Rows[j].FindControl("lbDG") as Label;
                        if (Session["lang"].ToString() == "VN")
                        {
                            int s = int.Parse(dt.Rows[j].ItemArray[5].ToString());
                            lb.Text = s.ToString("##,## VNÐ");
                            lb = GridGioHang.Rows[j].FindControl("lbThanhTien") as Label;
                            s = int.Parse(dt.Rows[j].ItemArray[7].ToString());
                            lb.Text = s.ToString("##,## VNÐ");
                        }
                        else
                        {
                            int s = int.Parse(dt.Rows[j].ItemArray[5].ToString());
                            lb.Text = s.ToString("##,## VNÐ");
                            lb = GridGioHang.Rows[j].FindControl("lbThanhTien") as Label;
                            s = int.Parse(dt.Rows[j].ItemArray[7].ToString());
                            lb.Text = s.ToString("##,## VNÐ");
                        }
                        sum += float.Parse(dt.Rows[j].ItemArray[7].ToString());
                    }
                    if (Session["lang"].ToString() == "VN")
                    {
                        lblSum.Text = "Tổng: <span style='color:red;font-weight:bold;'>" + sum.ToString("##,## VNÐ") + "</span>";
                        lbThanhTien.Text = "Tổng: <span style='color:green;font-weight:bold;'>" + NumberToStringVN.DocTienBangChu((decimal)sum, " đồng") + "</span";
                    }
                    else
                    {
                        lblSum.Text = "Total: <span style='color:red;font-weight:bold;'>" + sum.ToString("##,## USD") + "</span>";
                    }
                }
            }
            else
            {
                if (Session["lang"].ToString() == "VN")
                    lbl.Text = "Chua có sản phẩm nào trong giỏ hàng!!";
                else
                    lbl.Text = "Your Cart is Empty!!";
                lblSum.Text = "";
                //lbThanhtoan.Visible = false;
            }
        }
        public void LoadThongTinThanhToan()
        {
            if(Session["lang"].ToString() == "VN")
                lblThongTinThanhToan.Text = new sysConfigBL().Select(new sysConfigDO { ConfigID = 5 }).ConfigValue;
            else
                lblThongTinThanhToan.Text = new sysConfigBL().Select(new sysConfigDO { ConfigID = 5 }).eConfigValue;
        }

        protected void GridGioHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridGioHang.PageIndex = e.NewPageIndex;
            loadGioHang();
        }

        protected void GridGioHang_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }
        public static String Address
        {
            get
            {
                SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                return cfg.Network.UserName;
            }
        }
        public static String Pass
        {
            get
            {
                SmtpSection cfg = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
                return cfg.Network.Password;
            }
        }
        public void sendsMail(String addr, String name, String bd, string title)
        {
            SmtpClient SmtpServer = new SmtpClient();
            SmtpServer.Credentials = new System.Net.NetworkCredential(Address, Pass);
            SmtpServer.Port = 587;
            SmtpServer.Host = "Smtp.gmail.com";
            SmtpServer.EnableSsl = true;
            MailMessage mail = new MailMessage();
            try
            {
                mail.From = new MailAddress(addr, name, System.Text.Encoding.UTF8);
                mail.To.Add(addr);
                mail.Subject = title;
                mail.Body = bd;
                mail.IsBodyHtml = true;
                mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                SmtpServer.Send(mail);
            }
            catch (Exception ex)
            {
            }
        }
        public cmsGioHangDO init()
        {
            HttpSessionState ss = HttpContext.Current.Session;
            string session = ss.SessionID;

            cmsGioHangDO objGioHang = new cmsGioHangDO();
            if (Session["IDDN"] != null)
            {
                obj = new ClientLoginBL().Select(new ClientLoginDO { ClientLoginID = int.Parse(Session["IDDN"].ToString()) });
            }
            else
            {
                obj.ClientLoginID = 0;
                obj.ClientName = txtHT.Text;
                obj.Email = txtEmail.Text;
                obj.Mobile = txtsdt.Text;
                obj.Address = txtDC.Text;
            }
            objGioHang.ClientLoginID = obj.ClientLoginID;
            objGioHang.HinhThucThanhToan = txtHTTT.Text;
            objGioHang.NgayDatHang = DateTime.Now;
            objGioHang.SessionID = session;
            objGioHang.XuLy = false;

            return objGioHang;
        }

        protected void btn_Click(object sender, EventArgs e)
        {
            cmsGioHangDO objGioHang = init();
            bool kt = false;
            int kq = 0;
            float sum = 0;
            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    objGioHang.SanPhamID = Int64.Parse(dr[1].ToString());
                    objGioHang.SoLuong = Int32.Parse(dr[4].ToString());
                    objGioHang.NgayDatHang = DateTime.Now;
                    objGioHang.NgayGiaoHang = Convert.ToDateTime(txtNgayGiaoHang.Text);
                    objGioHang.XuLy = false;
                    objGioHang.ThanhTien = float.Parse(dr[7].ToString());
                    if (Session["lang"].ToString() == "VN")
                        objGioHang.TienTe = "VNĐ";
                    else
                        objGioHang.TienTe = "USD";
                    sum += float.Parse(dr[7].ToString());
                    kq = new cmsGioHangBL().Insert(objGioHang);
                }
                catch(Exception ee)
                {
                    kt = true;
                }
            }
            if (kt == false)
            {
                cmsDonHangDO objDonHang = new cmsDonHangDO();
                objDonHang.HoTen = txtHT.Text;
                objDonHang.DiaChiGiaoHang = txtDCGH.Text;
                objDonHang.DiaChi = txtDC.Text;
                objDonHang.Email = txtEmail.Text;
                objDonHang.GhiChu = txtGC.Text;
                objDonHang.HTTT = txtHTTT.Text;
                objDonHang.SDT = txtsdt.Text;
                objDonHang.SessionID = objGioHang.SessionID;
                objDonHang.TongTien = sum;
                objDonHang.UserID = 0;
                objGioHang.XuLy = true;
                if (Session["lang"].ToString() == "VN")
                    objDonHang.TienTe = "VNĐ";
                else
                    objDonHang.TienTe = "USD";

                kq = new cmsDonHangBL().Insert(objDonHang);
                objDonHang.XuLy = true;

                new cmsGioHangBL().Update(objGioHang);
                Session["GioHang"] = null;
                try
                {
                    string body1 = "Có đơn đặt hàng từ " + objDonHang.HoTen + "<br /> Email: " + objDonHang.Email;
                    if (Session["lang"].ToString() == "VN")
                    {
                        string body = "Chào bạn, bạn nhận được email này vì đã tiến hành đặt hàng trên website http://kma.vn. Chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất.";
                        sendsMail(objDonHang.Email,"kma.vn", body, "Đơn đặt hàng kma.vn");
                        sendsMail(new sysConfigBL().Select(new sysConfigDO { ConfigID = 3 }).ConfigName, objDonHang.HoTen, body1, "Đơn đặt hàng kma.vn" + kq);
                        //SessionIDManager Manager = new SessionIDManager();
                        //Session.Timeout = 1;
                        Session.Abandon();
                        Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
                        //Session.RemoveAll();
                        //Session.Clear();
                        Ultility.Alert("Bạn đã đặt hàng thành công!!", "/Default.aspx");
                    }
                    else
                    {
                        string body = "Hello, you receive this email since carried on the website http://kma.vn order. We will contact you as soon as possible.";
                        sendsMail(objDonHang.Email, "kma.vn", body, "Ordered kma.vn");
                        sendsMail(new sysConfigBL().Select(new sysConfigDO { ConfigID = 3 }).ConfigName, objDonHang.HoTen, body1, "Đơn đặt hàng kma.vn" + kq);
                        Session.Abandon();
                        Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
                        //Session.RemoveAll();
                        Session["lang"] = "EN";
                        Ultility.Alert("You have successfully ordered!!!", "/Default.aspx");
                    }
                }
                catch { }
            }
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            Response.Redirect("/GioHang.aspx");
        }
    }
}
